package com.alm.token.api;

import android.util.Log;

import com.alm.token.ConStant;
import com.alm.token.MyApp;
import com.alm.token.utils.LanguageUtils;
import com.alm.token.utils.LogUtil;
import com.alm.token.utils.SpUtil;

import java.io.IOException;
import java.util.HashSet;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by en on 2018/12/29.
 */

public class AddCookiesInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        HashSet<String> preferences = (HashSet) MyApp.context.getSharedPreferences("config",
                MyApp.context.MODE_PRIVATE).getStringSet("cookie", null);
        if (preferences != null) {
            for (String cookie : preferences) {
                if(cookie.indexOf("lang=")==-1){
                    cookie=cookie+"; "+SpUtil.getString(MyApp.context, ConStant.COOKIELANGAUE, ""+ LanguageUtils.COOKIE_CHINESE);
                }
                builder.addHeader("Cookie", cookie);
                LogUtil.v( "OkHttp:"+"Adding Header: " + cookie); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
            }
        }else {
            LogUtil.v( "OkHttp:"+"Adding Header: " + null); // This is done so I know which headers are being added; this interceptor is used after the normal logging of OkHttp
        }
        return chain.proceed(builder.build());
    }
}
